﻿using System;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Collections;
using YuuzleComic.Model;
using YuuzleComic.DBUtility;
using YuuzleComic.IDAL;
using System.Net;
using System.IO;

namespace YuuzleComic.SQLServerDAL
{
    public class Collect : DbBase, ICollect
    {
        public DataTable GetFolderSitePage(int FolderID, int PageIndex, int PageSize, out int RecordCount, out int PageCount)
        {

            if (FolderID < 1)
            {
                SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
                cn.Open();
                int nf = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, "select count(*) from Collect_SiteFolder where ChannelID='0'", null));
                int ns = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, "select count(*) from Collect_Site where ChannelID='0' and (Folder is null or Folder=0)", null));
                RecordCount = nf + ns;
                if (RecordCount % PageSize == 0)
                    PageCount = RecordCount / PageSize;
                else
                    PageCount = RecordCount / PageSize + 1;
                if (PageIndex > PageCount)
                    PageIndex = PageCount;
                if (PageIndex < 1)
                    PageIndex = 1;
                int nStart = PageSize * (PageIndex - 1);
                string Sql = "(select 0 as TP,ID,SiteFolder as SName,'' as objURL,'' as LockState from Collect_SiteFolder where ChannelID='0') union (select 1 as TP,ID,SiteName as SName,objURL,case when LinkSetting is null or PagebodySetting is null or  PageTitleSetting is null then '无效' else '有效' end as LockState from Collect_Site where ChannelID='0' and (Folder is null or Folder=0))";
                SqlDataAdapter ap = new SqlDataAdapter(Sql, cn);
                DataSet st = new DataSet();
                ap.Fill(st, nStart, PageSize, "REST");
                DataTable tb = st.Tables[0];
                st.Dispose();
                if (cn.State == ConnectionState.Open)
                    cn.Close();
                return tb;
            }
            else
            {
                return DbHelper.ExecutePage(DbHelperSQL.connectionString, "1 as TP,ID,SiteName as SName,objURL,case when LinkSetting is null or PagebodySetting is null or  PageTitleSetting is null then '无效' else '有效' end as LockState", "Collect_Site where ChannelID='0' and Folder=" + FolderID, "ID", "Order by ID", PageIndex, PageSize, out RecordCount, out PageCount, null);
            }
        }
        public void SiteCopy(int id)
        {
            SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
            cn.Open();
            try
            {
                string Sql = "select * from Collect_Site where ChannelID='0' and ID=" + id;
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                string snm = "", Column = "";
                if (rd.Read())
                {
                    snm = rd["SiteName"].ToString();
                    for (int i = 0; i < rd.FieldCount; i++)
                    {
                        string clnm = rd.GetName(i);
                        if (!(clnm.Equals("ID") || clnm.Equals("SiteName")))
                        {
                            Column += "," + clnm;
                        }
                    }
                }
                else
                {
                    rd.Close();
                    throw new Exception("0%没有找到该记录");
                }
                rd.Close();
                string snewnm = "复件 " + snm;
                int n = 2;
                while (Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, "select count(*) from Collect_Site where SiteName='" + snewnm + "'", null)) > 0)
                {
                    snewnm = "复件(" + n + ") " + snm;
                    n++;
                }
                Sql = "insert into Collect_Site (SiteName" + Column + ") select '" + snewnm + "' as NewName" + Column + " from Collect_Site where ChannelID='0' and ID=" + id;
                DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public void FolderCopy(int id)
        {
            SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
            cn.Open();
            try
            {
                string Sql = "select SiteFolder from Collect_SiteFolder where ChannelID='0' and ID=" + id;
                object snm = DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                if (snm == null)
                    throw new Exception("没有找到相关目录的记录");
                int n = 2;
                string snewnm = "复件 " + snm;
                /*
                if (Regex.Match(snm,@"^复件\s").Success)
                {
                    snewnm = "复件(" + n + ")" + snm;
                    n++;
                }
                else if (Regex.Match(snm, @"^复件(/d)").Success)
                {
                    n = int.Parse(Regex.Match(snm, @"(?<=复件\()\d+?(?=\).+)").Value);
                    n++;
                    snewnm = "复件(" + n + ")" + snm;
                    n++;
                }
                else
                {
                    snewnm = "复件 " + snm;
                }
                 */
                while (Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, "select count(*) from Collect_SiteFolder where SiteFolder='" + snewnm + "'", null)) > 0)
                {
                    snewnm = "复件(" + n + ") " + snm;
                    n++;
                }
                Sql = "insert into Collect_SiteFolder (SiteFolder,SiteFolderDetail,ChannelID) select '" + snewnm + "' as NewName,SiteFolderDetail,ChannelID from Collect_SiteFolder where ChannelID='0' and ID=" + id;
                DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public void FolderDelete(int id)
        {
            SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
            cn.Open();
            try
            {
                string Sql = "select count(*) from Collect_Site where ChannelID='0' and Folder=" + id;
                int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null));
                if (n > 0)
                    throw new Exception("该栏目下有站点,不能删除!");
                Sql = "Delete from Collect_SiteFolder where ChannelID='0' and ID=" + id;
                DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public void SiteDelete(int id)
        {
            SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
            cn.Open();
            SqlTransaction tran = cn.BeginTransaction();
            try
            {
                string[] Sql = new string[2];
                DbHelper.ExecuteNonQuery(tran, CommandType.Text, "Delete from Collect_RuleApply where SiteID=" + id, null);
                DbHelper.ExecuteNonQuery(tran, CommandType.Text, "Delete from Collect_Site where ChannelID='0' and ID=" + id, null);
                tran.Commit();
            }
            catch
            {
                tran.Rollback();
                throw;
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public DataTable GetFolder(int id, bool all)
        {
            string Sql = "select ID,SiteFolder,SiteFolderDetail from Collect_SiteFolder where ChannelID='0'";
            if (!all)
                Sql += " and ID=" + id;
            return DbHelper.ExecuteTable(DbHelperSQL.connectionString, CommandType.Text, Sql, null);
        }
        public DataTable GetSite(int id)
        {
            string Sql = "select a.*,b.OldContent,b.ReContent,b.IgnoreCase from Collect_Site a left join (Collect_Rule b inner join Collect_RuleApply c on b.ID=c.RuleID) on c.SiteID=a.ID where a.ChannelID='0' and a.ID=" + id;
            return DbHelper.ExecuteTable(DbHelperSQL.connectionString, CommandType.Text, Sql, null);
        }
        public int SiteAdd(CollectSiteInfo st)
        {
            SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
            cn.Open();
            try
            {
                string Sql = "select count(*) from Collect_Site where ChannelID='0' and SiteName=@SiteName";
                SqlParameter parm = new SqlParameter("@SiteName", SqlDbType.NVarChar, 50);
                parm.Value = st.SiteName;
                int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, parm));
                if (n > 0)
                {
                    cn.Close();
                    return 0;
                    //throw new Exception("采集站点名称重复!");
                }
                Sql = "insert into Collect_Site (";
                Sql += "SiteName,objURL,Folder,SaveRemotePic,Audit,IsReverse,IsAutoPicNews,TextTF";
                Sql += ",IsStyle,IsDIV,IsA,IsClass,IsFont,IsSpan,IsObject,IsIFrame,IsScript,Encode,ClassID,ChannelID) values (";
                Sql += "@SiteName,@objURL,@Folder,@SaveRemotePic,@Audit,@IsReverse,@IsAutoPicNews,@TextTF";
                Sql += ",@IsStyle,@IsDIV,@IsA,@IsClass,@IsFont,@IsSpan,@IsObject,@IsIFrame,@IsScript,@Encode,@ClassID,'0')";
                Sql += ";SELECT @@IDENTITY";
                int result = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, GetParameters(st)));
                return result;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public int FolderAdd(string Name, string Description)
        {
            SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
            cn.Open();
            string Sql = "select count(*) from Collect_SiteFolder where ChannelID='0' and SiteFolder=@SiteFolder";
            SqlParameter prm = new SqlParameter("@SiteFolder", SqlDbType.NVarChar, 50);
            prm.Value = Name;
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, prm));
            if (n > 0)
            {
                cn.Close();
                throw new Exception("栏目名称重复");
            }
            Sql = "insert into Collect_SiteFolder (SiteFolder,SiteFolderDetail,ChannelID) values (@SiteFolder,@SiteFolderDetail,'0');SELECT @@IDENTITY";
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@SiteFolder", SqlDbType.NVarChar, 50);
            param[0].Value = Name;
            param[1] = new SqlParameter("@SiteFolderDetail", SqlDbType.NText);
            param[1].Value = Description.Trim().Equals("") ? DBNull.Value : (object)Description;
            n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, param));
            cn.Close();
            return n;
        }
        public void SiteUpdate(CollectSiteInfo st, int step)
        {
            SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
            cn.Open();
            try
            {
                SqlParameter[] param = null;
                string Sql = "";
                if (step == 1)
                {
                    #region 第一步
                    Sql = "select count(*) from Collect_Site where SiteName=@SiteName and ChannelID='0' and ID<>@ID";
                    SqlParameter[] parm = new SqlParameter[2];
                    parm[0] = new SqlParameter("@SiteName", SqlDbType.NVarChar, 50);
                    parm[0].Value = st.SiteName;
                    parm[1] = new SqlParameter("@ID", SqlDbType.Int);
                    parm[1].Value = st.ID;
                    int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, parm));
                    if (n > 0)
                    {
                        cn.Close();
                        throw new Exception("采集站点名称重复!");
                    }
                    Sql = "update Collect_Site Set SiteName=@SiteName,objURL=@objURL,Folder=@Folder,ClassID=@ClassID,";
                    Sql += "SaveRemotePic=@SaveRemotePic,Audit=@Audit,IsReverse=@IsReverse,IsAutoPicNews=@IsAutoPicNews,TextTF=@TextTF,";
                    Sql += "IsStyle=@IsStyle,IsDIV=@IsDIV,IsA=@IsA,IsClass=@IsClass,IsFont=@IsFont,IsSpan=@IsSpan,";
                    Sql += "IsObject=@IsObject,IsIFrame=@IsIFrame,IsScript=@IsScript,Encode=@Encode where ChannelID='0' and ID=" + st.ID;
                    param = GetParameters(st);
                    #endregion 第一步
                }
                else if (step == 2)
                {
                    #region 第二步
                    Sql = "update Collect_Site set ListSetting=@ListSetting,OtherPageSetting=@OtherPageSetting,";
                    Sql += "StartPageNum=@StartPageNum,EndPageNum=@EndPageNum,OtherType=@OtherType where ChannelID='0' and ID=" + st.ID;
                    param = new SqlParameter[5];
                    param[0] = new SqlParameter("@ListSetting", SqlDbType.NVarChar, 4000);
                    param[0].Value = st.ListSetting;
                    param[1] = new SqlParameter("@OtherPageSetting", SqlDbType.NVarChar, 4000);
                    param[1].Value = st.OtherPageSetting.Trim().Equals("") ? DBNull.Value : (object)st.OtherPageSetting;
                    param[2] = new SqlParameter("@StartPageNum", SqlDbType.Int);
                    param[2].Value = st.StartPageNum < 0 ? DBNull.Value : (object)st.StartPageNum;
                    param[3] = new SqlParameter("@EndPageNum", SqlDbType.Int);
                    param[3].Value = st.EndPageNum < 0 ? DBNull.Value : (object)st.EndPageNum;
                    param[4] = new SqlParameter("@OtherType", SqlDbType.Int);
                    param[4].Value = st.OtherType;
                    #endregion 第二步
                }
                else if (step == 3)
                {
                    #region 第三步
                    Sql = "update Collect_Site set LinkSetting=@LinkSetting where ChannelID='0' and ID=" + st.ID;
                    param = new SqlParameter[1];
                    param[0] = new SqlParameter("@LinkSetting", SqlDbType.NVarChar, 4000);
                    param[0].Value = st.LinkSetting;
                    #endregion 第三步
                }
                else if (step == 4)
                {
                    #region 第四步
                    Sql = "Update Collect_Site set PageTitleSetting=@PageTitleSetting,PagebodySetting=@PagebodySetting";
                    Sql += ",AuthorSetting=@AuthorSetting,SourceSetting=@SourceSetting,AddDateSetting=@AddDateSetting,HandSetAuthor=@HandSetAuthor";
                    Sql += ",HandSetSource=@HandSetSource,HandSetAddDate=@HandSetAddDate,OtherNewsType=@OtherNewsType";
                    Sql += ",OtherNewsPageSetting=@OtherNewsPageSetting where ChannelID='0' and ID=" + st.ID;
                    param = new SqlParameter[10];
                    param[0] = new SqlParameter("@PageTitleSetting", SqlDbType.NVarChar, 4000);
                    param[0].Value = st.PageTitleSetting;
                    param[1] = new SqlParameter("@PagebodySetting", SqlDbType.NVarChar, 4000);
                    param[1].Value = st.PagebodySetting;
                    param[2] = new SqlParameter("@AuthorSetting", SqlDbType.NVarChar, 4000);
                    param[2].Value = st.AuthorSetting.Equals("") ? DBNull.Value : (object)st.AuthorSetting;
                    param[3] = new SqlParameter("@SourceSetting", SqlDbType.NText);
                    param[3].Value = st.SourceSetting.Equals("") ? DBNull.Value : (object)st.SourceSetting;
                    param[4] = new SqlParameter("@AddDateSetting", SqlDbType.NText);
                    param[4].Value = st.AddDateSetting.Equals("") ? DBNull.Value : (object)st.AddDateSetting;
                    param[5] = new SqlParameter("@HandSetAuthor", SqlDbType.NVarChar, 100);
                    param[5].Value = st.HandSetAuthor.Equals("") ? DBNull.Value : (object)st.HandSetAuthor;
                    param[6] = new SqlParameter("@HandSetSource", SqlDbType.NVarChar, 100);
                    param[6].Value = st.HandSetSource.Equals("") ? DBNull.Value : (object)st.HandSetSource;
                    param[7] = new SqlParameter("@HandSetAddDate", SqlDbType.DateTime);
                    param[7].Value = (st.HandSetAddDate.Year < 1753) ? DBNull.Value : (object)st.HandSetAddDate;
                    param[8] = new SqlParameter("@OtherNewsType", SqlDbType.Int);
                    param[8].Value = st.OtherNewsType;
                    param[9] = new SqlParameter("@OtherNewsPageSetting", SqlDbType.NVarChar, 4000);
                    param[9].Value = st.OtherNewsPageSetting.Trim().Equals("") ? DBNull.Value : (object)st.OtherNewsPageSetting;
                    #endregion 第四步
                }
                DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, param);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public void FolderUpdate(int id, string Name, string Description)
        {
            SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
            cn.Open();
            string Sql = "select count(*) from Collect_SiteFolder where SiteFolder=@SiteFolder and ChannelID='0' and ID<>" + id;
            SqlParameter prm = new SqlParameter("@SiteFolder", SqlDbType.NVarChar, 50);
            prm.Value = Name;
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, prm));
            if (n > 0)
            {
                cn.Close();
                throw new Exception("栏目名称重复");
            }
            Sql = "update Collect_SiteFolder set SiteFolder=@SiteFolder,SiteFolderDetail=@SiteFolderDetail where ChannelID='0' and ID=" + id;
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@SiteFolder", SqlDbType.NVarChar, 50);
            param[0].Value = Name;
            param[1] = new SqlParameter("@SiteFolderDetail", SqlDbType.NText);
            param[1].Value = Description.Trim().Equals("") ? DBNull.Value : (object)Description;
            DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, param);
            cn.Close();
        }
        private SqlParameter[] GetParameters(CollectSiteInfo st)
        {
            SqlParameter[] pmt = new SqlParameter[19];
            pmt[0] = new SqlParameter("@SiteName", SqlDbType.NVarChar, 50);
            pmt[0].Value = st.SiteName;
            pmt[1] = new SqlParameter("@objURL", SqlDbType.NVarChar, 250);
            pmt[1].Value = st.objURL;
            pmt[2] = new SqlParameter("@Folder", SqlDbType.Int);
            pmt[2].Value = st.Folder < 1 ? DBNull.Value : (object)st.Folder;
            pmt[3] = new SqlParameter("@SaveRemotePic", SqlDbType.Bit);
            pmt[3].Value = st.SaveRemotePic;
            pmt[4] = new SqlParameter("@Audit", SqlDbType.NVarChar, 10);
            pmt[4].Value = st.Audit;
            pmt[5] = new SqlParameter("@IsReverse", SqlDbType.Bit);
            pmt[5].Value = st.IsReverse;
            pmt[6] = new SqlParameter("@IsAutoPicNews", SqlDbType.Bit);
            pmt[6].Value = st.IsAutoPicNews;
            pmt[7] = new SqlParameter("@ClassID", SqlDbType.NVarChar, 50);
            pmt[7].Value = st.ClassID;
            pmt[8] = new SqlParameter("@TextTF", SqlDbType.Bit);
            pmt[8].Value = st.TextTF;
            pmt[9] = new SqlParameter("@IsStyle", SqlDbType.Bit);
            pmt[9].Value = st.IsStyle;
            pmt[10] = new SqlParameter("@IsDIV", SqlDbType.Bit);
            pmt[10].Value = st.IsDIV;
            pmt[11] = new SqlParameter("@IsA", SqlDbType.Bit);
            pmt[11].Value = st.IsA;
            pmt[12] = new SqlParameter("@IsClass", SqlDbType.Bit);
            pmt[12].Value = st.IsClass;
            pmt[13] = new SqlParameter("@IsFont", SqlDbType.Bit);
            pmt[13].Value = st.IsFont;
            pmt[14] = new SqlParameter("@IsSpan", SqlDbType.Bit);
            pmt[14].Value = st.IsSpan;
            pmt[15] = new SqlParameter("@IsObject", SqlDbType.Bit);
            pmt[15].Value = st.IsObject;
            pmt[16] = new SqlParameter("@IsIFrame", SqlDbType.Bit);
            pmt[16].Value = st.IsIFrame;
            pmt[17] = new SqlParameter("@IsScript", SqlDbType.Bit);
            pmt[17].Value = st.IsScript;
            pmt[18] = new SqlParameter("@Encode", SqlDbType.NVarChar, 50);
            pmt[18].Value = st.Encode;
            return pmt;
        }
        public DataTable GetRulePage(int PageIndex, int PageSize, out int RecordCount, out int PageCount)
        {
            return DbHelper.ExecutePage(DbHelperSQL.connectionString, "ID,RuleName,AddDate", "Collect_Rule where ChannelID='0'", "ID", "Order by ID", PageIndex, PageSize, out RecordCount, out PageCount, null);
        }
        public void RuleDelete(int id)
        {
            SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
            cn.Open();
            SqlTransaction trans = cn.BeginTransaction();
            try
            {
                string Sql = "delete from Collect_RuleApply where RuleID=" + id;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                Sql = "delete from Collect_Rule where ChannelID='0' and ID=" + id;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                trans.Commit();
            }
            catch
            {
                trans.Rollback();
                throw;
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public int RuleAdd(string Name, string OldStr, string NewStr, int[] AppSites, bool IgnoreCase)
        {
            int id = 0;
            SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
            cn.Open();
            string Sql = "select count(*) from Collect_Rule where RuleName=@RuleName and ChannelID='0'";
            SqlParameter param = new SqlParameter("@RuleName", SqlDbType.NVarChar, 50);
            param.Value = Name;
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, param));
            if (n > 0)
            {
                cn.Close();
                throw new Exception("规则名称重复");
            }
            SqlTransaction Trans = cn.BeginTransaction();
            try
            {
                Sql = "insert into Collect_Rule (RuleName,OldContent,ReContent,AddDate,IgnoreCase,ChannelID) values (@RuleName,@OldContent,@ReContent,@AddDate,@IgnoreCase,'0')";
                Sql += ";SELECT @@IDENTITY";
                SqlParameter[] parm = new SqlParameter[5];
                parm[0] = new SqlParameter("@RuleName", SqlDbType.NVarChar, 50);
                parm[0].Value = Name;
                parm[1] = new SqlParameter("@OldContent", SqlDbType.NVarChar, 100);
                parm[1].Value = OldStr;
                parm[2] = new SqlParameter("@ReContent", SqlDbType.NVarChar, 100);
                parm[2].Value = NewStr;
                parm[3] = new SqlParameter("@AddDate", SqlDbType.DateTime);
                parm[3].Value = DateTime.Now;
                parm[4] = new SqlParameter("@IgnoreCase", SqlDbType.Bit);
                parm[4].Value = IgnoreCase;
                id = Convert.ToInt32(DbHelper.ExecuteScalar(Trans, CommandType.Text, Sql, parm));
                if (AppSites != null && AppSites.Length > 0)
                {
                    foreach (int stid in AppSites)
                    {
                        Sql = "delete from Collect_RuleApply where SiteID=" + stid;
                        DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, null);
                        Sql = "insert into Collect_RuleApply(SiteID,RuleID,RefreshTime) values (" + stid + "," + id + ",'" + DateTime.Now + "')";
                        DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, null);
                    }
                }
                Trans.Commit();
            }
            catch
            {
                Trans.Rollback();
                throw;
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
            return id;
        }
        public void RuleUpdate(int RuleID, string Name, string OldStr, string NewStr, int[] AppSites, bool IgnoreCase)
        {
            SqlConnection cn = new SqlConnection(DbHelperSQL.connectionString);
            cn.Open();
            string Sql = "select count(*) from Collect_Rule where RuleName=@RuleName and ChannelID='0' and ID<>" + RuleID;
            SqlParameter param = new SqlParameter("@RuleName", SqlDbType.NVarChar, 50);
            param.Value = Name;
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, param));
            if (n > 0)
            {
                cn.Close();
                throw new Exception("规则名称重复");
            }
            SqlTransaction Trans = cn.BeginTransaction();
            try
            {
                Sql = "update Collect_Rule set RuleName=@RuleName,OldContent=@OldContent,ReContent=@ReContent,IgnoreCase=@IgnoreCase where ChannelID='0' and ID=" + RuleID;
                SqlParameter[] parm = new SqlParameter[4];
                parm[0] = new SqlParameter("@RuleName", SqlDbType.NVarChar, 50);
                parm[0].Value = Name;
                parm[1] = new SqlParameter("@OldContent", SqlDbType.NVarChar, 100);
                parm[1].Value = OldStr;
                parm[2] = new SqlParameter("@ReContent", SqlDbType.NVarChar, 100);
                parm[2].Value = NewStr;
                parm[3] = new SqlParameter("@IgnoreCase", SqlDbType.Bit);
                parm[3].Value = IgnoreCase;
                DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, parm);
                Sql = "delete from Collect_RuleApply where RuleID=" + RuleID;
                DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, null);
                if (AppSites != null && AppSites.Length > 0)
                {
                    foreach (int stid in AppSites)
                    {
                        Sql = "delete from Collect_RuleApply where SiteID=" + stid;
                        DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, null);
                        Sql = "insert into Collect_RuleApply(SiteID,RuleID,RefreshTime) values (" + stid + "," + RuleID + ",'" + DateTime.Now + "')";
                        DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, null);
                    }
                }
                Trans.Commit();
            }
            catch
            {
                Trans.Rollback();
                throw;
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public DataTable GetRule(int id)
        {
            string Sql = "select * from Collect_Rule where ChannelID='0' and ID=" + id;
            return DbHelper.ExecuteTable(DbHelperSQL.connectionString, CommandType.Text, Sql, null);
        }
        //获得过滤规则和过滤应用到的站点
        public DataTable GetRuleApplyList()
        {
            string Sql = "select * from Collect_Rule a inner join Collect_RuleApply b on a.ID = b.RuleID";
            return DbHelper.ExecuteTable(DbHelperSQL.connectionString, CommandType.Text, Sql, null);
        }
        public DataTable SiteList()
        {
            string Sql = "select a.id,SiteName,RuleID from Collect_Site a left outer join Collect_RuleApply b on a.ID = b.SiteID where a.ChannelID='0'";
            return DbHelper.ExecuteTable(DbHelperSQL.connectionString, CommandType.Text, Sql, null);
        }
        public void NewsAdd(CollectNewsInfo newsinfo)
        {
            string Sql = "insert into Collect_News ([Title],[Links],[Author],[Source],[Content],[AddDate],[ImagesCount],[SiteID],[History],[ReviewTF],[CollectTime],[ChannelID],[ClassID],[ParentID]) values (";
            Sql += "@Title,@Links,@Author,@Source,@Content,@AddDate,@ImagesCount,@SiteID,0,0,'" + DateTime.Now + "','0',@ClassID,@ParentID)";
            DbHelper.ExecuteNonQuery(DbHelperSQL.connectionString, CommandType.Text, Sql, GetNewsParams(newsinfo));
        }
        public void NewsReset(int id)
        {
            string Sql = "update Collect_News set history=0 where id=" + id;
            DbHelper.ExecuteNonQuery(DbHelperSQL.connectionString, CommandType.Text, Sql);
        }
        public bool TitleExist(string title)
        {
            string Sql = "select count(id) from Collect_News where Title=@Title ";
            SqlParameter Param = new SqlParameter("@Title", title);
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(DbHelperSQL.connectionString, CommandType.Text, Sql, Param));
            if (n > 0)
                return true;
            else
                return false;
        }
        public DataTable GetSameComic(string trueTitle)
        {
            string Sql = "select * from Collect_News where Title like @Title and (ParentID=0 or ParentID is null) order by ID desc";
            SqlParameter Param = new SqlParameter("@Title", trueTitle + "[[]%]");
            return DbHelper.ExecuteTable(DbHelperSQL.connectionString, CommandType.Text, Sql, Param);
        }
        public void UpdateChapterParentID(int oldid, int newid) {
            string Sql = "update Collect_News set parentid=@newid where parentid=@oldid";
            SqlParameter[] Param = new SqlParameter[]{
                new SqlParameter("@newid", newid),
                new SqlParameter("@oldid", oldid)
            };
            DbHelper.ExecuteNonQuery(DbHelperSQL.connectionString, CommandType.Text, Sql, Param);
        }

        public bool ChapterTitleExist(string title, int ParentID)
        {
            string Sql = "select count(id) from Collect_News where Title=@Title and ParentID=@ParentID";
            SqlParameter[] Param = new SqlParameter[]{
                new SqlParameter("@Title", title),
                new SqlParameter("@ParentID", ParentID)
            };
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(DbHelperSQL.connectionString, CommandType.Text, Sql, Param));
            if (n > 0)
                return true;
            else
                return false;
        }
        public bool ChapterCollectExist(string SiteID)
        {
            string Sql = "select count(id) from Collect_Site where ParentID=@ParentID";
            SqlParameter Param = new SqlParameter("@ParentID", SiteID);
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(DbHelperSQL.connectionString, CommandType.Text, Sql, Param));
            if (n > 0)
                return true;
            else
                return false;
        }
        public int GetChapterCollectID(int SiteID)
        {
            string Sql = "select top(1) id from Collect_Site where ParentID=@ParentID";
            SqlParameter Param = new SqlParameter("@ParentID", SiteID);
            IDataReader rd = DbHelper.ExecuteReader(DbHelperSQL.connectionString, CommandType.Text, Sql, Param);
            if (rd.Read())
            {
                return rd.GetInt32(0);
            }
            return 0;
        }
        public DataTable GetNewsPage(int PageIndex, int PageSize, string query, out int RecordCount, out int PageCount)
        {
            return DbHelper.ExecutePage(DbHelperSQL.connectionString, "a.ID,Title,AddDate,SiteName,History,CollectTime,SiteID,Links", "Collect_News a left join Collect_Site b on a.SiteID=b.ID where a.ChannelID='0' and a.Title like '%" + query + "%' and (a.ParentID is null or a.ParentID=0)", "a.ID", "Order by History asc,a.ID desc", PageIndex, PageSize, out RecordCount, out PageCount, null);
        }
        public DataTable GetChapterPage(int PageIndex, int PageSize, string query, out int RecordCount, out int PageCount)
        {
            string s = "";
            if (!string.IsNullOrEmpty(query))
            {
                s = " and a.ParentID = " + query;
            }
            else
            {
                s = " and (a.ParentID is not null and a.ParentID<>0)";
            }
            return DbHelper.ExecutePage(DbHelperSQL.connectionString, "a.ID,Title,AddDate,SiteName,History,CollectTime,SiteID,Links,ImagesCount", "Collect_News a left join Collect_Site b on a.SiteID=b.ID where a.ChannelID='0'" + s, "a.ID", "Order by History asc,a.ID desc", PageIndex, PageSize, out RecordCount, out PageCount, null);
        }
        public void NewsDelete(string id)
        {
            string Sql = "Delete from Collect_News where ChannelID='0'";
            if (id.Equals("0"))
                Sql += " and History=1";
            else
                Sql += " and ID in (" + id + ")";
            DbHelper.ExecuteNonQuery(DbHelperSQL.connectionString, CommandType.Text, Sql, null);
        }        
        public void NewsDeleteParentID(string parentid)
        {
            string Sql = "Delete from Collect_News where ChannelID='0'";
            if (parentid.Equals("0"))
                Sql += " and History=1";
            else
                Sql += " and parentid in (" + parentid + ")";
            DbHelper.ExecuteNonQuery(DbHelperSQL.connectionString, CommandType.Text, Sql, null);
        }
        public CollectNewsInfo GetNews(int id)
        {
            CollectNewsInfo info = new CollectNewsInfo();
            string Sql = "select [Title],[Links],[SiteID],[Author],[Source],[AddDate],[Content],[CollectTime],[ClassID],[History] from Collect_News where ChannelID='0' and ID=" + id;
            IDataReader rd = DbHelper.ExecuteReader(DbHelperSQL.connectionString, CommandType.Text, Sql, null);
            if (rd.Read())
            {
                info.Title = rd.GetString(0);
                info.Links = rd.GetString(1);
                info.SiteID = rd.GetInt32(2);
                if (!rd.IsDBNull(3)) info.Author = rd.GetString(3);
                if (!rd.IsDBNull(4)) info.Source = rd.GetString(4);
                if (!rd.IsDBNull(5)) info.AddDate = rd.GetDateTime(5);
                if (!rd.IsDBNull(6)) info.Content = rd.GetString(6);
                info.CollectTime = rd.GetDateTime(7);
                info.ClassID = rd.GetString(8);
                info.History = rd.GetBoolean(9);
            }
            rd.Close();
            return info;
        }
        public void NewsUpdate(int id, CollectNewsInfo info)
        {
            string Sql = "update Collect_News set [Title]=@Title,[Links]=@Links,[SiteID]=@SiteID,[Author]=@Author";
            Sql += ",[Source]=@Source,[AddDate]=@AddDate,[Content]=@Content,[ClassID]=@ClassID,[History]=@History where ChannelID='0' and ID=" + id;
            DbHelper.ExecuteNonQuery(DbHelperSQL.connectionString, CommandType.Text, Sql, GetNewsParams(info));
        }
        private SqlParameter[] GetNewsParams(CollectNewsInfo info)
        {
            if (info.Author == null)
            {
                info.Author = "";
            }
            if (info.Source == null)
            {
                info.Source = "";
            }
            //if (info.AddDate == null)
            //{
            info.AddDate = DateTime.Now;
            //}
            SqlParameter[] param = new SqlParameter[11];
            param[0] = new SqlParameter("@Title", SqlDbType.NVarChar, 100);
            param[0].Value = info.Title;
            param[1] = new SqlParameter("@Links", SqlDbType.NVarChar, 200);
            param[1].Value = info.Links;
            param[2] = new SqlParameter("@Author", SqlDbType.NVarChar, 100);
            param[2].Value = info.Author.Trim().Equals("") ? DBNull.Value : (object)info.Author;
            param[3] = new SqlParameter("@Source", SqlDbType.NVarChar, 100);
            param[3].Value = info.Source.Trim().Equals("") ? DBNull.Value : (object)info.Source;
            param[4] = new SqlParameter("@Content", SqlDbType.NText);
            param[4].Value = info.Content;
            param[5] = new SqlParameter("@AddDate", SqlDbType.DateTime);
            param[5].Value = info.AddDate.Year < 1753 ? DBNull.Value : (object)info.AddDate;
            param[6] = new SqlParameter("@SiteID", SqlDbType.Int);
            param[6].Value = info.SiteID;
            param[7] = new SqlParameter("@ClassID", SqlDbType.NVarChar, 12);
            param[7].Value = info.ClassID;
            param[8] = new SqlParameter("@ImagesCount", SqlDbType.Int);
            param[8].Value = info.ImagesCount;
            param[9] = new SqlParameter("@ParentID", SqlDbType.Int);
            param[9].Value = info.ParentID;
            param[10] = new SqlParameter("@History", SqlDbType.Bit);
            param[10].Value = info.History;
            return param;
        }
        #region 新闻入库
        ///////////////////////////新闻入库专用///////////////////////////////////////
        private SqlConnection connetion;
        private SqlConnection confoosun;
        private int nStoreSucceed = 0;
        private int nStoreFailed = 0;
        public void StoreNews(bool UnStore, int[] id, out int nSucceed, out int nFailed)
        {
            nSucceed = 0;
            nFailed = 0;
            connetion = new SqlConnection(DbHelperSQL.connectionString);
            confoosun = new SqlConnection(DbHelperSQL.connectionString);
            string Sql = "select a.ID,a.Title,a.Links,a.Author,a.Source,a.Content,a.AddDate,a.RecTF,a.TodayNewsTF,a.MarqueeNews,a.SiteID";
            Sql += ",a.SBSNews,a.ReviewTF,a.ClassID,b.Audit,a.ImagesCount,b.IsAutoPicNews from Collect_News a inner join Collect_Site b";
            Sql += " on a.SiteID=b.ID where a.ChannelID='0' and (a.ParentID is null or a.ParentID=0)";
            try
            {
                connetion.Open();
                confoosun.Open();
                if (UnStore)
                {
                    Sql += " and History=0";
                }
                else
                {
                    string strid = "";
                    for (int i = 0; i < id.Length; i++)
                    {
                        if (i > 0)
                            strid += ",";
                        strid += id[i].ToString();
                    }
                    Sql += " and a.id in (" + strid + ")";
                }
                StoreStep(Sql);
                nSucceed = nStoreSucceed;
                nFailed = nStoreFailed;
            }
            finally
            {
                StoreEnd();
            }
        }
        private void StoreStep(string Sql)
        {
            int IsAudit = 3;
            //int AID = 0;
            //object obj = DbHelper.ExecuteScalar(confoosun, CommandType.Text, "select max(id) from comics", null);
            //if (obj != null && obj != DBNull.Value)
            //    AID = Convert.ToInt32(obj);
            //AID++;
            DataTable dt = DbHelper.ExecuteTable(connetion, CommandType.Text, Sql, null);
            CollectNewsInfo Info = new CollectNewsInfo();
            foreach (DataRow r in dt.Rows)
            {
                try
                {
                    bool isExistedClassID = true;//将要入库新闻的栏目ID是否有效
                    int id = Convert.ToInt32(r["id"]);
                    //bool isEnd = true;
                    string sTitle = r["Title"].ToString().Trim();
                    string sClass = r["ClassID"].ToString();
                    string sContent = r["Content"].ToString();
                    string sLinks = r["Links"].ToString();
                    string imagesCount = r["ImagesCount"].ToString();
                    string isAutoPicNews = r["IsAutoPicNews"].ToString();
                    string sAuthor = "";
                    if (r["Author"] != DBNull.Value) sAuthor = r["Author"].ToString();
                    string sSource = "";
                    if (r["Source"] != DBNull.Value) sSource = r["Source"].ToString();
                    DateTime dtAddDate = DateTime.Now;
                    if (r["AddDate"] != DBNull.Value) dtAddDate = DateTime.Parse(r["AddDate"].ToString());
                    IsAudit = (int)r["Audit"];
                    string[] others = sSource.Split('^');

                    string picUrl = "";
                    string NewsType = "0";
                    //设置新闻的类型，是否是图片新闻
                    if (!string.IsNullOrEmpty(isAutoPicNews) && isAutoPicNews.Equals("True"))
                    {
                        try
                        {
                            int imgCou = Convert.ToInt32(imagesCount);
                            if (imgCou > 0)
                            {
                                NewsType = "1";//设置为图片新闻
                                string re = "<img[^>]* src=\"([^\"]*)\"[^>]*>";
                                Regex regex = new Regex(re, RegexOptions.IgnoreCase);
                                MatchCollection collection = regex.Matches(sContent);
                                Match ma = collection[0];
                                picUrl = ma.Groups[1].Value;
                            }
                        }
                        catch
                        {
                            //图片数量错误
                        }
                    }

                    string CheckSate = "3|1|1|1";
                    int IsLock = 1;
                    switch (IsAudit)
                    {
                        case 0:
                            CheckSate = "0|0|0|0";
                            IsLock = 0;
                            break;
                        case 1:
                            CheckSate = "1|1|0|0";
                            break;
                        case 2:
                            CheckSate = "2|1|1|0";
                            break;
                    }
                    #region 取新闻的默认值选项
                    //#region 用于保存新闻的变量
                    //string NewsPathRule = string.Empty;
                    //string NewsFileRule = string.Empty;
                    //byte isDelPoint = 0;
                    //int Gpoint = 0;
                    //int iPoint = 0;
                    //string GroupNumber = string.Empty;
                    //string FileExName = ".html";
                    //string DataLib = "news";
                    //string Temp = string.Empty;
                    //string ClassEname = string.Empty;
                    //#endregion 用于保存新闻的变量
                    //Sql = "select NewsSavePath,NewsFileRule,isDelPoint,Gpoint,iPoint,GroupNumber,FileName,DataLib,ReadNewsTemplet,ClassEName";
                    //Sql += " from news_Class where ClassID='" + sClass + "'";
                    //IDataReader rd = DbHelper.ExecuteReader(confoosun, CommandType.Text, Sql, null);
                    //if (rd.Read())
                    //{
                    //    #region 赋值
                    //    ClassEname = rd["ClassEName"].ToString();
                    //    if (rd["NewsSavePath"] != DBNull.Value)
                    //        NewsPathRule = rd["NewsSavePath"].ToString();
                    //    if (rd["NewsFileRule"] != DBNull.Value)
                    //        NewsFileRule = rd["NewsFileRule"].ToString();
                    //    if (rd["isDelPoint"] != DBNull.Value)
                    //        isDelPoint = Convert.ToByte(rd["isDelPoint"]);
                    //    if (rd["Gpoint"] != DBNull.Value)
                    //        Gpoint = Convert.ToInt32(rd["Gpoint"]);
                    //    if (rd["iPoint"] != DBNull.Value)
                    //        iPoint = Convert.ToInt32(rd["iPoint"]);
                    //    if (rd["GroupNumber"] != DBNull.Value)
                    //        GroupNumber = rd["GroupNumber"].ToString();
                    //    if (rd["FileName"] != DBNull.Value)
                    //        FileExName = rd["FileName"].ToString();
                    //    if (rd["DataLib"] != DBNull.Value)
                    //        DataLib = rd["DataLib"].ToString();
                    //    if (rd["ReadNewsTemplet"] != DBNull.Value)
                    //        Temp = rd["ReadNewsTemplet"].ToString();
                    //    #endregion 赋值
                    //}
                    //else
                    //{
                    //    nStoreFailed++;
                    //    isExistedClassID = false;
                    //}
                    //rd.Close();
                    //if (isExistedClassID)
                    //{
                    //    #region 保存的文件名等的计算
                    //    string SavePath = ExChangeRule(NewsPathRule, sClass, ClassEname, 0);
                    //    string FileName = ExChangeRule(NewsFileRule, sClass, ClassEname, 0);
                    //    string NewsID = Common.Rand.Number(12);
                    //    if (FileName == string.Empty)
                    //        FileName = YuuzleComic.Common.Rand.Number(12);
                    //    while (Convert.ToInt32(DbHelper.ExecuteScalar(confoosun, CommandType.Text, "select count(ID) from news where NewsID='" + NewsID + "' or FileName='" + FileName + "'", null)) > 0)
                    //    {
                    //        NewsID = YuuzleComic.Common.Rand.Number(12, true);
                    //        FileName = FileName + "_" + YuuzleComic.Common.Rand.Number(3, true);
                    //    }
                    //    #endregion
                    #endregion 取新闻的默认值选项

                    DataSet ds;
                    #region 处理地区问题
                    int dqid = 0;
                    diqu diqubll = new diqu();
                    ds = diqubll.GetList("diqu='" + others[3] + "'");
                    if (ds.Tables[0].Rows.Count == 1)
                    {
                        dqid = Convert.ToInt32(ds.Tables[0].Rows[0]["id"]);
                    }
                    #endregion

                    #region 处理作者问题
                    int zzid = 39;
                    zz zzbll = new zz();
                    if (!string.IsNullOrEmpty(sAuthor) && sAuthor != "未知")
                    {
                        if (!zzbll.Exists(sAuthor))
                        {
                            Model.zz zzobj = new Model.zz();
                            zzobj.zzmc = sAuthor;
                            zzobj.zzjs = "            <h1 class=\"blue\">" + zzobj.zzmc + "</h1>";
                            zzobj.dqid = dqid;
                            zzobj.zztp = "none.jpg";
                            zzobj.zm = YuuzleComic.Common.Chs2Spell.GetHeadOfChs(sAuthor.Substring(0, 1));
                            zzid = zzbll.Add(zzobj);
                        }
                        else
                        {
                            YuuzleComic.Model.zz zzmodel = zzbll.GetModel(sAuthor);
                            zzid = Convert.ToInt32(zzmodel.id);
                        }
                    }
                    #endregion

                    #region 处理漫画情况
                    int comicid = 0;
                    comics comicbll = new comics();
                    Model.comics comics = new Model.comics();
                    comics.classid = Convert.ToInt32(sClass);
                    comics.mhmc = sTitle;//漫画名称
                    comics.zzid = zzid;//作者
                    comics.dqid = dqid; //地区
                    comics.zm = others[4];//首字母
                    comics.zt = others[1] == "完结"; //是否完结
                    comics.tj = others[2] == "i5"; //是否推荐
                    comics.mhjs = sContent.Replace("(本漫画内容介绍由xindm.cn整理提供)",""); //漫画介绍
                    comics.mhjj = YuuzleComic.Common.Input.GetSubString(YuuzleComic.Common.Input.FilterHTML(comics.mhjs).Trim(), 300, "…");
                    comics.mhtc = others[5].Replace("&nbsp;", " ").Trim();
                    comics.mhbm = others[6];
                    comics.cjid = Convert.ToInt32(r["SiteID"]);//采集规则编码
                    comics.cjitemid = r["ID"].ToString();//采集漫画表编码
                    if (!comicbll.Exists(sTitle))
                    {
                        #region 添加漫画
                        comics.adddate = DateTime.Now;
                        ds = DbHelperSQL.Query("select top(1) text from segment order by newid()");
                        comics.mhjs = comics.mhjs.Trim() + "<br/>" + ds.Tables[0].Rows[0][0].ToString();
                        comicid = comicbll.Add(comics);
                        #endregion
                    }
                    else
                    {
                        ds = comicbll.GetList("mhmc = '" + sTitle.Replace("'", "''") + "'");
                        if (ds.Tables[0].Rows.Count == 1)
                        {
                            comicid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                            Sql = "update comics set tj=" + (comics.tj ? 1 : 0) + ",zt=" + (comics.zt ? 1 : 0) + ",mhtc='" + comics.mhtc + "',cjid='" + r["SiteID"] + "' , cjitemid='" + r["ID"] + "' where ID=" + comicid;
                            DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql);
                        }
                    }
                    #region 保存封面
                    string filename = comicid + System.IO.Path.GetExtension(others[0]);
                    if (!System.IO.File.Exists(filename))
                    {
                        Common.Input.SaveRemoteResource("/cpic", sLinks, others[0], comicid.ToString());
                    }
                    Sql = "update comics set mhfm='" + filename + "' where ID=" + comicid;
                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, null);
                    #endregion
                    #endregion

                    Sql = "update Collect_News set History=1 where ID=" + id;
                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, null);

                    Sql = "select * from Collect_News where ParentID=" + id + " order by ID desc";
                    DataTable zjdt = DbHelper.ExecuteTable(connetion, CommandType.Text, Sql, null);
                    if (zjdt != null && zjdt.Rows.Count > 0)
                    {
                        zj zjdal = new zj();
                        foreach (DataRow dr in zjdt.Rows)
                        {
                            if (!zjdal.Exists(dr["Title"].ToString(), comicid) && !Convert.ToBoolean(dr["History"]))
                            {
                                Model.zj zjobj = new Model.zj();
                                zjobj.cid = comicid;
                                zjobj.zjmc = dr["Title"].ToString().Trim();
                                zjobj.tpadd = "";
                                zjobj.tps = Convert.ToInt32(dr["ImagesCount"]);
                                zjobj.tpf = 0;
                                zjobj.time = DateTime.Now;
                                //zjobj.tpurl = Common.Input.GetImagesSrc(dr["Content"].ToString());
                                zjobj.tpurl = dr["Content"].ToString();
                                string url = zjobj.tpurl.Split('|')[0];
                                if (!string.IsNullOrEmpty(url) && url.Length > 1)
	                            {
                                    string[] urlArr = url.Substring(0, url.LastIndexOf("/")).Split('/');
                                    for (int i = 2; i < urlArr.Length; i++)
                                    {
                                        zjobj.tpadd += System.Web.HttpUtility.UrlDecode(urlArr[i]) + "/";
                                    }
	                            }
                                zjobj.cjitemid = Convert.ToInt32(dr["id"]);

                                string zjmc_temp = zjobj.zjmc;
                                foreach (string s in new string[]{"清晰版","KC","正式版"})
                                {
                                    zjmc_temp = zjmc_temp.Replace(s, "").Trim();
                                }
                                if (zjdal.ExistsAdd(zjobj.tpadd, comicid))
                                {
                                    Sql = "update zj set zjmc='" + zjobj.zjmc + "' where tpadd='" + zjobj.tpadd + "' and cid=" + comicid;
                                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, null);
                                }
                                else if (zjdal.Exists(zjmc_temp, comicid))
                                {
                                    DataSet dszj = zjdal.GetList("zjmc='" + zjmc_temp + "' and cid=" + comicid);
                                    if (dszj.Tables[0].Rows.Count==1)
                                    {
                                        zjobj.id = Convert.ToInt32(dszj.Tables[0].Rows[0]["id"]);
                                        zjdal.Update(zjobj);
                                    }
                                }
                                else
                                {
                                    zjdal.Add(zjobj);
                                }
                            }
                            Sql = "update Collect_News set History=1 where ID=" + dr["id"].ToString();
                            DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, null);
                        }
                    }

                    nStoreSucceed++;
                    //AID++;
                }
                catch(Exception ex)
                {
                    //string text = ex.ToString();
                    //StreamWriter streamw = File.CreateText(@"C:\web\YuuzleComic\test.txt");
                    //streamw.WriteLine(text);
                    //streamw.Close(); 
                    nStoreFailed++;
                }
            }
            dt.Clear();
            dt.Dispose();
        }
        private void StoreEnd()
        {
            if (connetion != null && connetion.State == ConnectionState.Open)
                connetion.Close();
            if (confoosun != null && confoosun.State == ConnectionState.Open)
                confoosun.Close();
        }
        private string ExChangeRule(string RuleStr, string classid, string classename, int autoid)
        {
            string RetVal = string.Empty;
            if (RuleStr != null && RuleStr != string.Empty)
            {
                RetVal = RuleStr;
                DateTime Now = DateTime.Now;
                RetVal = Regex.Replace(RetVal, @"\{\@year02\}", Now.Year.ToString().Substring(2, 2), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@year04\}", Now.Year.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@month\}", Now.Month.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@day\}", Now.Day.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@hour\}", Now.Hour.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@minute\}", Now.Minute.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@second\}", Now.Second.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@ClassId\}", classid, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@EName\}", classename, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                Regex reg = new Regex(@"\{\@Ram(?<m>\d+)_(?<n>\d+)\}", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                Match match = reg.Match(RetVal);
                while (match.Success)
                {
                    int m = Convert.ToInt32(match.Groups["m"].Value);
                    int n = Convert.ToInt32(match.Groups["n"].Value);
                    string s = match.Value;
                    string rnd = string.Empty;
                    switch (n)
                    {
                        case 0:
                            rnd = YuuzleComic.Common.Rand.Number(m);
                            break;
                        case 1:
                            rnd = YuuzleComic.Common.Rand.Str_char(m);
                            break;
                        case 2:
                            rnd = YuuzleComic.Common.Rand.Str(m);
                            break;
                    }
                    RetVal = RetVal.Replace(s, rnd);
                    match = reg.Match(RetVal);
                }
                RetVal = Regex.Replace(RetVal, @"\{\@自动编号ID\}", autoid.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
            }
            return RetVal;
        }
        #endregion 新闻入库

        public DataTable GetAllNewsLinks(string NewsIDs)
        {
            string Sql = "SELECT id,Links,SiteID FROM Collect_News where ChannelID='0' and (ParentID=0 or ParentID is null)";
            if (!string.IsNullOrEmpty(NewsIDs))
            {
                Sql += " and id in (" + NewsIDs + ")";
            }
            else
            {
                //Sql += " and (ParentID is null or ParentID=0)";
                Sql += " and ID not in (SELECT distinct ParentID FROM Collect_News where ChannelID='0' and (ParentID is not null and ParentID<>0))";
            }
            return DbHelper.ExecuteTable(DbHelperSQL.connectionString, CommandType.Text, Sql, null);
        }

        public int GetNewsTotalCount()
        {
            return Convert.ToInt32(DbHelper.ExecuteScalar(DbHelperSQL.connectionString, CommandType.Text, "select count(id) from Collect_News where ChannelID='0' and (ParentID is null or ParentID=0)", null));
        }

        public DataTable GetIdsByNewsUrl(string[] NewsUrl) {
            string Sql = "select id from Collect_News where Links in(";
            foreach (string item in NewsUrl)
            {
                Sql += "'" + item + "',";
            }
            Sql = Sql.Remove(Sql.Length - 1);
            Sql += ")";
            return DbHelper.ExecuteTable(DbHelperSQL.connectionString, CommandType.Text, Sql);
        }

    }
}
